package com.example.testdemo.service;

import com.example.testdemo.dao.UserDao;
import com.example.testdemo.dto.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureQuery;
import java.util.List;
import java.util.Optional;
/**
 * @Author: chengxuefei
 * @Date: 2021/7/2 0026
 * @Time: 15:23
 */
@Transactional( rollbackFor = Exception.class)
@Service
public class UserService {

    @Resource
    EntityManager entityManager;
    @Resource
    private UserDao userDao;


    @Transactional(rollbackFor = Exception.class)
    public void add(User user) {
        userDao.save(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(User user) {
        userDao.delete(user);
    }
    public void update(User user) {
        userDao.save(user);
    }
    public Long testfun(Integer abc){
        StoredProcedureQuery storedProcedure =entityManager.createStoredProcedureQuery("increment2");
        storedProcedure.registerStoredProcedureParameter("test1", Integer.class, ParameterMode.IN);
        storedProcedure.registerStoredProcedureParameter("test2", Integer.class, ParameterMode.OUT);
        //参数赋值
        storedProcedure.setParameter("test1",abc);
        storedProcedure.execute();
        Object test2 = storedProcedure.getOutputParameterValue("test2");
        return Long.parseLong(test2.toString());
    }

    public User findById(String userId) {
        Optional<User> user = userDao.findById(userId);
        return user.orElse(null);
    }
    public Long testABS(Integer id) {
        Long aLong = userDao.testFun(id);
        return aLong;
    }

    public Page<User> findListPage(int page,int size){
        return userDao.findAll(PageRequest.of(page,size));
    }
}
